<template>
  <div class="tabsMain flex align-center justify-between">
      <el-tabs v-if="tagsList.length > 0" v-model="currentActive" type="card" closable @tab-remove="removeTab" @tab-click="clickTab">
        <el-tab-pane
          v-for="item in tagsList"
          :key="item.name"
          :label="item.meta.title"
          :name="item.path"
        >
        </el-tab-pane>
      </el-tabs>
      <el-button v-if="tagsList.length > 0" type="text" icon="el-icon-circle-plus" @click="newQueryHandle">新建查询</el-button>
  </div>
</template>
<script>
import {mapGetters} from "vuex";

export default {
  name: 'Tabs',
  data() {
    return {
    }
  },
  computed: {
    ...mapGetters(['tagsList', 'currentActive', 'currentDatabase'])
  },
  created() {
    let tagsList = localStorage.getItem('tagsList');
    if(tagsList) {
      try {
        tagsList = JSON.parse(tagsList);
        this.$store.commit('ADD_TAGSLIST', tagsList)
      } catch (e) {
        this.$store.commit('ADD_TAGSLIST', [])
      }
    }

    let currentActive = localStorage.getItem('currentActive');
    if(currentActive) {
      this.$store.commit('SET_CURRENTACTIVE', currentActive);
    }

    let currentDatabase = localStorage.getItem('currentDatabase');
    if(currentDatabase) {
      this.$store.commit('SET_CURRENTDATABASE', currentDatabase);
    }
  },
  methods: {
    removeTab(targetName) {
      let index = this.tagsList.findIndex(item => item.path === targetName);
      this.$store.commit('DEL_TAGSLIST', index);
      if (this.tagsList.length > 0) {
        this.$router.push(`/index${this.tagsList[this.tagsList.length - 1].path}`);
        this.$store.commit('SET_CURRENTACTIVE', this.tagsList[this.tagsList.length - 1].path);
      } else {
        this.$router.push('/');
      }
    },
    clickTab(tab) {
      this.$router.push(`/index${tab.name}`);
      this.$store.commit('SET_CURRENTACTIVE', tab.name);
    },
    newQueryHandle(){
      this.$store.commit('ADD_TAGSLIST', {
        name: 'newQuery',
        path: '/newQuery',
        meta: {
          title: `${this.currentDatabase}-新建查询`
        }
      })
      this.$store.commit('SET_CURRENTACTIVE', '/newQuery');
      this.$router.push('/index/newQuery')
    }
  }
}
</script>
<style lang="scss" scoped>
.tabsMain{
  position: relative;
  ::v-deep .el-tabs{
    width: 100%;
  }
  ::v-deep .el-button{
    position: absolute;
    right: 10px;
    top: 8px;
    padding: 0;
  }
}
</style>
